from fastapi import APIRouter, HTTPException, Request, Depends
from sqlalchemy.orm import Session
from uuid import uuid4
import json

from app.db import get_db, init_db, ProjectConfigRecord


router = APIRouter()


# 确保表已创建
init_db()


@router.post("/save-config")
async def save_config(request: Request, db: Session = Depends(get_db)):
    try:
        body = await request.body()
        # 保留原始字符串，避免编码差异；也可 json.dumps(await request.json(), ensure_ascii=False)
        data_str = body.decode('utf-8') if isinstance(body, (bytes, bytearray)) else str(body)
        step = request.query_params.get('step')
        rec = ProjectConfigRecord(
            id=uuid4().hex,
            step=step,
            data=data_str,
        )
        db.add(rec)
        db.commit()
        return {"id": rec.id}
    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=500, detail=str(e))


@router.post("/save-config/{config_id}")
async def update_config(config_id: str, request: Request, db: Session = Depends(get_db)):
    try:
        rec = db.get(ProjectConfigRecord, config_id)
        if not rec:
            raise HTTPException(status_code=404, detail="记录不存在")
        body = await request.body()
        rec.data = body.decode('utf-8') if isinstance(body, (bytes, bytearray)) else str(body)
        step = request.query_params.get('step')
        if step:
            rec.step = step
        db.add(rec)
        db.commit()
        return {"id": rec.id, "updated": True}
    except HTTPException:
        raise
    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/config/{config_id}")
def get_config(config_id: str, db: Session = Depends(get_db)):
    rec = db.get(ProjectConfigRecord, config_id)
    if not rec:
        raise HTTPException(status_code=404, detail="记录不存在")
    try:
        payload = json.loads(rec.data)
    except Exception:
        payload = rec.data
    return {
        "id": rec.id,
        "step": rec.step,
        "data": payload,
        "createdAt": rec.created_at,
        "updatedAt": rec.updated_at,
    }


@router.get("/configs")
def list_configs(limit: int = 50, db: Session = Depends(get_db)):
    q = db.query(ProjectConfigRecord).order_by(ProjectConfigRecord.created_at.desc()).limit(limit)
    items = []
    for rec in q.all():
        try:
            payload = json.loads(rec.data)
        except Exception:
            payload = rec.data
        items.append({
            "id": rec.id,
            "step": rec.step,
            "data": payload,
            "createdAt": rec.created_at,
            "updatedAt": rec.updated_at,
        })
    return {"items": items}
